<?php
App::uses('AppController', 'Controller');

class RegisterController extends AppController {

    public function beforeFilter()
    {
        parent::beforeFilter();

        // Change layout for Ajax requests
        if ($this->request->is('ajax')) {
                $this->layout = 'ajax';
        }
    }

    public function index() 
    {
		$this->layout = 'ajax';
    
        // form posted
        if ($this->request->is('post')) {
            
            if (!$this->Session->Check('Session.timestamp.register.' . $this->request->data['token'])) {
                $data = array(
                    'result' => false,
                    'msg' => __('regis_again'),
                );
				$this->set('data', $data);
                //return $this->response->body(json_encode($data));
            }
            $this->Session->delete('Session.timestamp.register.' . $this->request->data['token']);
            
            //check email exists
            $email = $this->Register->findByEmail($this->request->data['Register']['email']);
			$countRegis = $this->Register->find('count');
            $code='';
			if (empty($email)) 
            {
                $this->Register->create();//create
                //attempt to save
                if($countRegis < 500) {
					$code = $this->generateCode();
				}
				$this->request->data['Register']['code'] = $code;
                $this->Register->created = date('Y-m-d H:i:s');
                if ($this->Register->save($this->request->data)) {
                    if($this->sendMail($this->data, $countRegis)) {
						$data = array(
							'result' => true,
							'code' => $code,
						);
					} else {
						$data = array(
							'result' => false,
							'msg' => __('Email is incorrect'),
						);
					}
			
					$this->set('data', $data);
					//return $this->response->body(json_encode($data));
						
                } else {
                    $data = array(
                        'result' => false,
                        'msg' => __('Please input full and correct information'),
                    );
 
					$this->set('data', $data);
                    //return $this->response->body(json_encode($data));
                }
            } else {
                $data = array(
                    'result' => false,
                    'msg' => __('* The email has exists'),
                );
				
				$this->set('data', $data);
                //return $this->response->body(json_encode($data));
            }
            $lang = $this->Session->read('Config.language');
			$code='';
			if($lang == 'eng') $code ='_eng';
			$this->set('code', $code);
        }
    }

    public function sendMail($data, $countRegis) 
    {
        App::uses('CakeEmail', 'Network/Email');
        $email = new CakeEmail();
		$email->from(array('no-reply@ngayhoihong.vn' => __('email_name')));
        $email->to($data['Register']['email']);
        $email->viewVars(array('data' => $data['Register']));
        $email->emailFormat('html');
		if($countRegis < 500)
			$email->template('register');
		else 
			$email->template('no-register');
			
        $email->subject(__('email_subject'));
        if($email->send()) {
			return true;
		} else {
			return false;
		}
    }

    function generateCode ($length = 5){
        // inicializa variables
        $code = "";
        $i = 0;
        $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
        
        // agrega random
        while ($i < $length){
            $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
            
            if (!strstr($code, $char)) { 
                $code .= $char;
                $i++;
            }
        }
        return $code;
    }
	
	public function createToken() 
	{
		$this->layout = 'ajax';
		$this->autoRender = false;
		//create session token
        $sessionTimeStamp = Security::hash(date('Y-m-dH:i:s') . rand(5, 15), 'sha1', true);
        $this->Session->write('Session.timestamp.register.' . $sessionTimeStamp, 1);
		echo $sessionTimeStamp;return;
	}
}